package org.procrastinationapp.business.entities.user.repositories;

import org.procrastinationapp.business.entities.user.User;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.List;

public class UserRepository extends HibernateDaoSupport {

	private static final String QUERY_PASSWORD = "select PASSWORD from USER where login = ?";
	private static final String UPDATE_PASSWORD = "update USER set PASSWORD = ? where login = ?";

	private JdbcTemplate jdbcTemplate;

	@Required
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public String getPasswordForUser(String login) {
		return (String) jdbcTemplate.queryForObject(QUERY_PASSWORD,
				new Object[] { login }, String.class);
	}

	public void setPasswordForUser(String login, String newPasswordDigest) {
		jdbcTemplate.update(UPDATE_PASSWORD, new Object[] { newPasswordDigest,
				login });
	}

	@SuppressWarnings("unchecked")
	public List<User> getUsers() {
		return getHibernateTemplate().loadAll(User.class);
	}

	public User getUser(String login) {
		User user = (User) getHibernateTemplate().get(User.class, login);
		if (user == null) {
			throw new ObjectRetrievalFailureException(User.class, login);
		}
		return user;
	}

	public void saveUser(User user) {
		getHibernateTemplate().saveOrUpdate(user);
	}

	public void removeUser(String login) {
		getHibernateTemplate().delete(getUser(login));
	}
}
